package org.bees.cms.web.tag;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspWriter;

import net.sf.json.JSONObject;

import org.bees.cms.common.Tree;
import org.bees.cms.web.util.Beans;
import org.bees.cms.web.util.velocity.element.Link;

public class Location extends Tag {
	private static final long serialVersionUID = -9132027842108470738L;

	private Tree<?> node;
	private String title;
	private String arrow;
	private String link;
	private List<Link> links = new ArrayList<Link>();

	@Override
	protected void before() throws Exception {
		JSONObject object = JSONObject.fromObject(link);
		List<?> ancestors = node.ancestors();
		for (int i = ancestors.size() - 1; ancestors != null && i >= 0; i--) {
			Link link = new Link();
			link.from(object);
			Object node = ancestors.get(i);
			if (Beans.contains(node.getClass(), link.getText())) {
				link.setText(Beans.getString(node, link.getText()));
			}
			String value = Beans.getString(node, link.getProperty());
			String href = link.getAction() + (link.getAction().contains("?") ? "&" : "?") + link.getName() + "=" + value;
			link.setHref(href);
			links.add(link);
		}
	}

	@Override
	protected void analyze(JspWriter writer) throws Exception {
		writer.append("<div ");
		writer.append(" id='" + id + "'");
		writer.append(" clazz='" + clazz + "'");
		writer.append(" style='" + style + "'");
		writer.append(">");
		writer.append(title).append(" : ");
		for (int i = 0; i < links.size(); i++) {
			writer.append(links.get(i).toHTML());
			if (i != links.size() - 1) {
				writer.append(arrow);
			}
		}
		writer.append("</div>");
	}

	@Override
	protected void after() throws Exception {
		node = null;
		title = null;
		arrow = null;
		link = null;
		links.clear();
	}

	public Tree<?> getNode() {
		return node;
	}

	public void setNode(Tree<?> node) {
		this.node = node;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getArrow() {
		return arrow;
	}

	public void setArrow(String arrow) {
		this.arrow = arrow;
	}

	public String getLink() {
		return link;
	}

	public void setLink(String link) {
		this.link = link;
	}

	public List<Link> getLinks() {
		return links;
	}

	public void setLinks(List<Link> links) {
		this.links = links;
	}

}
